﻿using System;
using System.Configuration;
using System.Reflection;
using System.Linq;
using AutoMapper;
using iTelluro.Explorer.Infrastructure.CrossCutting.Adapter;

namespace iTelluro.Explorer.Infrastructure.CrossCutting.NetFramework.Adapter
{
    public class AutomapperTypeAdapterFactory
        :ITypeAdapterFactory
    {
        #region Constructor

        /// <summary>
        /// Create a AutoMapper type adapter factory
        /// </summary>
        public AutomapperTypeAdapterFactory()
        {
            //scan all assemblies finding Automapper Profile
            //var profiles = AppDomain.CurrentDomain
            //                        .GetAssemblies()
            //                        .SelectMany(a => a.GetTypes())
            //                        .Where(b => b.BaseType == typeof(Profile));
            string strAssembly = ConfigurationManager.AppSettings["ProfilesAssembly"];

            if (!string.IsNullOrWhiteSpace(strAssembly))
            {
                var profiles = Assembly.Load(strAssembly).GetTypes().Where(b => b.BaseType == typeof(Profile));
                Mapper.Initialize(cfg =>
                {
                    foreach (var item in profiles)
                    {
                        if (item.FullName != "AutoMapper.SelfProfiler`2")
                            cfg.AddProfile(Activator.CreateInstance(item) as Profile);
                    }
                });
            }
        }

        #endregion

        #region ITypeAdapterFactory 成员

        public ITypeAdapter Create()
        {
            return new AutomapperTypeAdapter();
        }

        #endregion
    }
}
